package logic

import (
	"context"
	"fmt"
	"strconv"
	"tb/cache"

	"tb/tbrpc/internal/svc"
	"tb/tbrpc/tbrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *tbrpc.CartListRequest) (*tbrpc.CartListResponse, error) {
	// todo: add your logic here and delete this line

	key := fmt.Sprintf("cart:%d:%d", in.UserId, in.ProductId)
	result, _ := cache.Rdb.Keys(l.ctx, key).Result()
	allPrice := 0.0
	var products []*tbrpc.CartList
	for _, s := range result {

		m, _ := cache.Rdb.HGetAll(l.ctx, s).Result()
		price, _ := strconv.Atoi(m["price"])
		number, _ := strconv.Atoi(m["number"])
		totalPrice := number * price
		allPrice += float64(totalPrice)
		list := tbrpc.CartList{
			Title:      m["title"],
			Price:      float32(price),
			Number:     int64(number),
			UserId:     m["userId"],
			ProductId:  m["productId"],
			TotalPrice: int64(totalPrice),
		}
		products = append(products, &list)

	}

	return &tbrpc.CartListResponse{
		List:     products,
		AllPrice: float32(allPrice),
	}, nil
}
